package com.lhl.jwt.security.provider;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.alibaba.fastjson.JSON;
import com.lhl.jwt.domain.entity.SysUser;
import com.lhl.jwt.excepiton.JwtException;
import com.lhl.jwt.security.token.MiniAppAuthenticationToken;
import com.lhl.jwt.service.AuthService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * @className: com.lhl.jwt.security.provider.MiniAppAuthenticationProvider
 * @description: TODO 类描述
 * @author: king
 * @date: 2020-12-21 15:09
 **/
@Api(tags = "MiniAppAuthenticationProvider", produces = "MiniAppAuthenticationProvider")
@Component
@Slf4j
public class MiniAppAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private AuthService authService;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        MiniAppAuthenticationToken miniAppAuthenticationToken = null;
        if (authentication instanceof MiniAppAuthenticationToken) {
            miniAppAuthenticationToken = (MiniAppAuthenticationToken) authentication;
        }
        SysUser sysUser = authService.findByOpenId(miniAppAuthenticationToken.getOpenid());
        //执行注册逻辑
        if (sysUser == null) {
            log.debug("account not exist, began to register. openid is [{}]", miniAppAuthenticationToken.getOpenid());
            //签名校验
            Digester digester = new Digester(DigestAlgorithm.SHA1);
            String data = miniAppAuthenticationToken.getRawData() + miniAppAuthenticationToken.getSessionKey();
            String signature = digester.digestHex(data);
            if (!miniAppAuthenticationToken.getSignature().equals(signature)) {
                log.error("signature is invalid, [{}] vs [{}]", signature, miniAppAuthenticationToken.getSignature());
                throw new JwtException(StrUtil.format("signature is invalid, {} vs {}", signature, miniAppAuthenticationToken.getSignature()));
            }
            //获取用户信息
            sysUser = JSON.parseObject(miniAppAuthenticationToken.getRawData(), SysUser.class);
            sysUser.setOpenid(miniAppAuthenticationToken.getOpenid());
            sysUser.setSessionKey(miniAppAuthenticationToken.getSessionKey());
            sysUser.setDeleted(0);
            log.info("account is [{}]", sysUser);
            sysUser = authService.register(sysUser);
            //获取权限
//            List<Permission> permissions = authService.acquirePermission(account.getAccountId());
//            List<SimpleGrantedAuthority> authorities = permissions.stream().map(permission -> new SimpleGrantedAuthority(permission.getPermission())).collect(Collectors.toList());
//            return new MiniAppAuthenticationToken(sysUser.getOpenid(), sysUser.getSessionKey(), authorities);
        }
        // 存在：获取权限
//        List<Permission> permissions = authService.acquirePermission(account.getAccountId());
//        List<SimpleGrantedAuthority> authorities = permissions.stream().map(permission -> new SimpleGrantedAuthority(permission.getPermission())).collect(Collectors.toList());
//        return new MiniAppAuthenticationToken(miniAppAuthenticationToken.getOpenid(), miniAppAuthenticationToken.getSessionKey(), authorities);
return null;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (MiniAppAuthenticationToken.class.isAssignableFrom(authentication));
    }
}
